import { _decorator, Button, Color, Component, director, EditBox, HorizontalTextAlignment, instantiate, JsonAsset, Label, Node, Overflow, Prefab, ScrollView, sys, UITransform } from 'cc';
import { Race } from './Race';
import { MG3 } from './MG3';
const { ccclass, property } = _decorator;

const userDataKey = 'userData';

interface UserData {
    name: string
    race: string
    startPoint: string
    curMap: string
}

@ccclass('CreatorPlay')
export class CreatorPlay extends Component {

    //从JSON文件加载玩家已解锁的种族
    @property(JsonAsset)
    racesData: JsonAsset = null!;
    //输入名称
    @property({ type: EditBox })
    public nameInputBox: EditBox = null;
    //打开列表选择种族
    @property({ type: Button })
    public SelectRaceBtn: Button = null;
    //打开列表选择出生点
    @property({ type: Button })
    public SelectStartPointBtn: Button = null;
    //创建成功按钮
    @property({ type: Button })
    public CreatCompBtn: Button = null;
    //退出创建按钮
    @property({ type: Button })
    public cleanBtn: Button = null;
    //种族列表视图
    @property({ type: ScrollView })
    public RaceList: ScrollView = null;
    //出生点列表视图
    @property({ type: ScrollView })
    public StartPointList: ScrollView = null;
    //列表显示预制体
    @property({ type: Prefab })
    itemPrefab: Prefab = null;
    //可选择种族数据
    raceItems: Race[] = [];
    //可选择出生点
    StartPointItems: { name: string, id: string }[] = [{ name: '盖亚大陆', id: 'worldRegion1' }, { name: '苍渊大陆', id: 'worldRegion2' }, { name: '热海大陆', id: 'worldRegion3' }];
    //玩家选择的种族的ID
    selectedRace: string = '人类';
    /**@param selectedStartPoint 玩家选择的出生点 */
    selectedStartPoint: string = 'worldRegion1';
    //可选择出生点数据
    //从JSON文件加载玩家已解锁的职业
    //

    //
    private raceDescNode: Node = null;
    private raceDescLabel: Label = null;

    start() {
        this.loadListData();
        this.CreatCompBtn.node.on('click', this.onCreatCompBtnClicked, this);
        this.SelectRaceBtn.node.on('click', this.onSelectRaceBtnClicked, this);
        this.SelectStartPointBtn.node.on('click', this.onStartPointBtnClicked, this);
        this.cleanBtn.node.on('click', () => { this.node.active = false }, this);
    }
    onSelectRaceBtnClicked() {
        // 清除布局中的所有子节点，即清除之前显示的所有物品
        this.RaceList.content.children.forEach(child => child.destroy());
        this.RaceList.node.getComponent(UITransform).width = 200;
        this.GenListData(this.RaceList, this.raceItems);
        this.node.parent.on('click', () => {
            this.node.active = false;
        }, this);
    }

    private n: number = 0;
    onStartPointBtnClicked() {
        this.n++
        this.SelectStartPointBtn.node.getChildByName('Label').getComponent(Label).string = this.StartPointItems[this.n].name;
        this.selectedStartPoint = this.StartPointItems[this.n].id;
        if (this.n === this.StartPointItems.length - 1) { this.n = -1 };
        console.log(this.SelectStartPointBtn + this.selectedStartPoint);
    }

    //单击创建成功按钮，使用sys.localStorage.setItem保存玩家数据Json文件到安卓专属存储路径
    onCreatCompBtnClicked() {
        //保存玩家创建的角色,加载生成世界，把玩家放入世界
        this.saveUserData();
        new MG3().loadDataGener(this.selectedStartPoint)
        director.loadScene('activeScene');
    }

    saveUserData() {
        const playName = this.nameInputBox.string;
        const userData = {
            name: playName,
            race: this.selectedRace,
            startPoint: this.selectedStartPoint,
            curMap: this.selectedStartPoint
        };
        const jsonStr = JSON.stringify(userData);
        sys.localStorage.setItem(userDataKey, jsonStr);
    }

    loadUserData() {

        const jsonStr = sys.localStorage.getItem(userDataKey);
        const userData = JSON.parse(jsonStr) as UserData;;
        console.log(userData);
    }

    //生成列表UI
    GenListData(list: ScrollView, items: Race[]) {
        for (let item of items) {
            // 实例化UI节点预制体
            const itemPrefab = instantiate(this.itemPrefab);
            // 获取物品预制体中的名称标签组件
            const nameLabel = itemPrefab.getChildByName('Label').getComponent(Label);
            // 设置名称标签的文本为物品名称和数量
            nameLabel.string = item.item_name;
            // 设置物品预制体的点击事件，点击时调用 onItemClicked 方法并传递当前物品作为参数
            itemPrefab.on('click', this.onItemClicked.bind(this, item.item_name, item.description));
            // 将物品预制体添加到布局中
            list.content.addChild(itemPrefab);
        }
    }

    loadListData() {
        //加载显示可选择种族列表
        const racejsonData = this.racesData.json!;
        this.raceItems = racejsonData.races.map(itemData => {
            // 假设 itemData 包含 name, description, itemType, quantity 等属性
            return new Race(itemData.name, itemData.description);
        });
        this.SelectRaceBtn.node.getChildByName("Label").getComponent(Label).string = this.raceItems[0].item_name;

        this.RaceList.content.addChild(this.newRaceraceDescNode(this.raceItems[0].description));

    }
    onItemClicked(name: string, description: string) {
        // 清除布局中的所有子节点，即清除之前显示的所有物品
        this.RaceList.content.children.forEach(child => child.destroy());
        //显示被选中种族的名字
        this.SelectRaceBtn.node.getChildByName("Label").getComponent(Label).string = name;
        //显示被选中种族的描述
        this.raceDescLabel.string = description;
        this.RaceList.content.addChild(this.newRaceraceDescNode(description));
        this.RaceList.node.getComponent(UITransform).width = 350;
        //记录玩家选择的种族
        this.selectedRace = name;
    }

    newRaceraceDescNode(raceDesc: string) {
        this.raceDescNode = new Node;
        this.raceDescNode.addComponent(UITransform).width = 300;
        this.raceDescLabel = this.raceDescNode.addComponent(Label);
        this.raceDescLabel.fontSize = 23;
        this.raceDescLabel.lineHeight = 30;
        this.raceDescLabel.color = new Color().fromHEX("#000000");
        this.raceDescLabel.horizontalAlign = HorizontalTextAlignment.LEFT;
        this.raceDescLabel.overflow = Overflow.RESIZE_HEIGHT;
        this.raceDescLabel.string = raceDesc;
        return this.raceDescNode;
    }
    update(deltaTime: number) {

    }

    //当我们不再需要一个存储条目时，可以通过下面的接口将其移除：sys.localStorage.removeItem(key)
    //当我们不再需要已存储的用户数据时，可以通过下面的接口将其清空：sys.localStorage.clear()
}


